package parser

import (
	"encoding/json"
	"fmt"
	"github.com/jmoiron/sqlx"
	"log"
	"my-crawler/concurrence/engine"
	"my-crawler/concurrence/fetcher"
	"my-crawler/concurrence/task"
	fun "my-crawler/concurrence/task/mohurd/common"
	"my-crawler/concurrence/task/mohurd/query"
	"my-crawler/database/mysql"
	"strconv"
)

//步骤1 获取comment_id
func ListParser(content []byte, ReqData engine.ReqData) engine.ParserResult {
	//解密字符出纳
	res := engine.ParserResult{}

	//获取下一页
	page, ok := ReqData.Payload["pg"]
	if !ok {
		log.Fatal("Not Found ID!")
	}
	atoi, _ := strconv.Atoi(page)

	reqData, header, reqUrl := query.GetReqData(strconv.Itoa(atoi + 1))
	//update
	if atoi < task.MEndPage {
		c := fun.DecodeDecryptString(content)
		result := query.Result{}
		err := json.Unmarshal([]byte(c), &result)
		if err != nil {
			log.Fatal(err)
		}
		//先插入到mohurd表
		client := mysql.Db
		InsertMohurd(client, result)
		//再请求详情页
		for _, v := range result.Data.List {
			//saver.InsertRowGu(v.CERTNUM, v.ROW_GU)
			reqData2, header2, reqUrl2 := query.GetDetailData(v.ROW_GU)
			//请求每个的详情 ROW_GUID
			//http://jzsc.mohurd.gov.cn/api/webApi/dataservice/query/project/ecLicenceDetail1?rowGu=242d4e45a5024f98acc1ef34bff1d168&pg=0&pgsz=5
			res.Request = append(res.Request, engine.CrawlerRequest{
				ReqData:  engine.CreateReqData(header2, reqData2, reqUrl2), //数据初始化
				HttpFunc: &fetcher.GetReq{},                                //添加上延迟时间 默认就使用之前的
				Parser:   ecLicenseDetailParser,
			})
		}

		//再追加列表页下一页请求
		res.Request = append(res.Request, engine.CrawlerRequest{
			ReqData:  engine.CreateReqData(header, reqData, reqUrl), //数据初始化
			HttpFunc: &fetcher.GetReq{},                             //添加上延迟时间 默认就使用之前的
			Parser:   ListParser,
		})

		return res
	}
	return engine.NilParserResult()
}
func InsertMohurd(db *sqlx.DB, res query.Result) {
	for _, i := range res.Data.List {
		r, err := db.Exec(
			"insert into mohurd(ROW_GU,工程名称, 建设地址, 工程项目编号,施工许可证电子证照编号,项目分类,"+
				"项目属地,建设单位代码,建设单位项目负责人,项目负责人证件号码,计划开工日期,计划竣工日期,合同价格,"+
				"总面积,合计地上面积,合计地下面积,发证机关代码,签发日期,管理属地,建设单位,发证机关,建设规模)"+
				"values(?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?)",
			i.ROW_GU, i.PROJNAME, i.PROJLOC, i.PRJNUM, i.CERTNUM, i.PRJTYPENUM, i.RISSUAUTH, i.PROJOWNERCODE, i.OWNERMNGR,
			i.OWNERMNGRCARDNO, i.PSTARTDATE, i.PCOMPDATE, i.CONPRICE, i.TOTALHAREA, i.TOTALAHAREA, i.TOTALUHAREA,
			i.ISSUAUTHCODE, i.ISSUDATE, i.RISSUAUTH, i.PROJOWNER, i.ISSUAUTH, i.PROJSCALE)
		if err != nil {
			fmt.Println("exec failed, ", err)
			return
		}
		_, err = r.LastInsertId()
		if err != nil {
			fmt.Println("exec failed, ", err)
			return
		}
	}

}
